package com.zmn.oms.business.impl.work.erp;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.business.interfaces.log.OrderQuotationLogBService;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.business.interfaces.work.erp.ErpPerformanceListBService;
import com.zmn.oms.common.constant.OmsErrorCodeConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.work.erp.OrderOnTimeDTO;
import com.zmn.oms.model.dto.work.erp.QuotationPerformanceDTO;
import com.zmn.oms.model.entity.changerecord.OrderChangeRecord;
import com.zmn.oms.model.entity.log.OrderLog;
import com.zmn.oms.model.entity.log.OrderQuotationLog;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.changerecord.OrderChangeRecordService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author sunlife
 * @date:2021/1/18 11:58 上午
 * description:
 */
@Service
public class ErpPerformanceListBServiceImpl implements ErpPerformanceListBService {

    @Autowired
    OrderWorkService orderWorkService;
    @Autowired
    OrderQuotationLogBService orderQuotationLogBService;
    @Autowired
    OrderLogBService orderLogBService;
    @Autowired
    OrderChangeRecordService orderChangeRecordService;
    @Autowired
    ServItemBService servItemBService;

    @Override
    public QuotationPerformanceDTO getQuotationPerformance(@NotNull(message = "订单号不能为空") Long orderId, @NotNull(message = "工单号不能为空") Long workId) throws OmsBaseException {
        QuotationPerformanceDTO dto = new QuotationPerformanceDTO();
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException("未查到工单相关信息");
        }

        Long scanId = orderWork.getVisitUserId();
        // 扫码状态
        Integer scanStatus = NumberUtil.isNullOrZero(scanId) ? GlobalConsts.NO : GlobalConsts.YES;
        dto.setScanStatus(scanStatus);

        // 扫码主体ID
        dto.setScanUserId(scanId);

        // 报价主体ID
        List<OrderQuotationLog> logs = orderQuotationLogBService.listByOrderIdAndWorkId(orderId, workId);
        if (CollectionUtil.isNotNullOrEmpty(logs)) {
            logs.stream().filter(log -> {
                return Objects.equals(log.getType(), OrderConsts.QUOTATION_END);
            }).max(Comparator.comparing(OrderQuotationLog::getCreateTime).reversed()).ifPresent(log -> {
                dto.setQuotationUserId(log.getUserId());
            });
            logs.stream().filter(log -> {
                return Objects.equals(log.getType(), OrderConsts.QUOTATION_START);
            }).max(Comparator.comparing(OrderQuotationLog::getCreateTime).reversed()).ifPresent(log -> {
                dto.setQuotationTime(DateUtil.dateFormatToDate(log.getStartTime(), DateUtil.FORMAT_DEFAULT));
            });
        }

        // 支付完成时间
        dto.setPayTime(orderWork.getPayTime());

        // 第一次收单完状态
        List<OrderLog> orderLogs = orderLogBService.findOrderLogsByWorkId(workId);
        orderLogs.stream().filter(log -> {
            return Objects.equals(log.getType(), OrderLogConsts.ORDER_LOG_TYPE_CHECKOUT);
        }).min(Comparator.comparing(OrderLog::getCreateTime)).ifPresent(log -> {
            Boolean checkOutSuccess = Objects.equals(log.getAfterResultStatus(), OrderStatusConsts.WORK_RESULT_SUCCESS);
           dto.setCheckOutSuccess(checkOutSuccess);
        });

        // 是否计价器类型
        dto.setUseTariff(servItemBService.isQuotationType(orderWork.getServItemType()));

        // 预付全款
        dto.setFullPaymentFlag(Optional.ofNullable(orderWork.getFullPaymentFlag()).orElse(GlobalConsts.NO));

        return dto;
    }

    @Override
    public OrderOnTimeDTO getOnTimePerformance(@NotNull(message = "订单号不能为空") Long orderId, @NotNull(message = "工单号不能为空") Long workId) throws OmsBaseException {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, workId);
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException(OmsErrorCodeConsts.ORDER_NOT_FOUND, "订单不存在");
        }
        OrderChangeRecord orderChangeRecord = orderChangeRecordService.getChangeRecordByOrderId(orderId);
        if (Objects.isNull(orderChangeRecord)) {
            throw new OmsBaseException("订单操作记录不存在");
        }

        OrderOnTimeDTO onTimeDTO = new OrderOnTimeDTO();
        onTimeDTO.setEngineerId(orderWork.getMasterId());
        // 是否改派
        onTimeDTO.setIsChangeDistribute(orderChangeRecord.getDistributeCount() > 0 ? GlobalConsts.YES : GlobalConsts.NO);

        // 最后改派的订单预约时间
        onTimeDTO.setLastDistributeTime(orderChangeRecord.getLastDistributeTime());

        // 是否工程师修改预约时间
        onTimeDTO.setIsEngineerModifyDutyTime(Objects.equals(orderChangeRecord.getLastDutyOptType(), GlobalConsts.OPERATE_USER_TYPE_MASTER) ? GlobalConsts.YES : GlobalConsts.NO);

        // 首次预约时间
        onTimeDTO.setFirstDutyTime(orderChangeRecord.getFirstDutyTime());
        // dutyTime
        onTimeDTO.setDutyTime(orderWork.getDutyTime());

        // 扫码时间
        onTimeDTO.setVisitScanTime(orderChangeRecord.getLastVisitScanTime());

        // 上传形象照时间
        onTimeDTO.setMasterImageTime(orderChangeRecord.getLastMasterImageTime());

        return onTimeDTO;
    }
}
